<template>
  <div>
    <div class="demo">
      <div class="content-wrapper">
        <h2>主应用 Vite+vue2</h2>
        <div class="navigation">
          <el-button @click="goBack" type="primary">返回首页</el-button>
          <!-- 新增的API请求按钮 -->
          <el-button @click="sendApiRequest" type="success">发送API请求</el-button>
          <div v-show="functionName" style="margin: 20px;" :style="{color:fontColor}">
            从react子应用获取的数据:
            <p>
              <strong>function call Name: </strong>{{ functionName }}
            </p>
            <p><strong>status: </strong>{{ context }}</p>
            <p><strong>finishTime: </strong>{{ dataTime }}</p>
          </div>
          <el-input v-model="inputText" placeholder="请输入" style="margin: 20px;"></el-input>
        </div>
      </div>
    </div>
    <div class="framework" id="react_container">
      <micro-app
        name="react-subapp"
        iframe
        :url="url"
        @datachange="handleDataChange"
        :data="inputTextForChild"
        router-mode="pure"
      ></micro-app>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "Demo",
  data() {
    return {
      functionName: "",
      context: "",
      inputText: "",
      dataTime: "",
      fontColor: "#000",
      url: `http://${window.location.hostname}:5174/Translator`
    };
  },
  computed: {
    inputTextForChild() {
      return { text: this.inputText };
    },
  },
  methods: {
    goBack() {
      this.$router.push("/");
    },
    async sendApiRequest() {
      try {
        const response = await axios.get('/test');
        console.log('API请求成功:', response.data);
        this.$message.success('API请求成功');
      } catch (error) {
        console.error('API请求失败:', error);
        this.$message.error('API请求失败: ' + error.message);
      }
    },
    handleDataChange(e) {
      console.log("来自子应用的数据：", e.detail.data);
      this.functionName = e.detail.data.functionName;
      this.context = e.detail.data.context;
      this.dataTime = new Date(e.detail.data.time).toLocaleString();
      if(this.functionName === 'set_font_color'){
        this.fontColor = this.context;
      }
    },
  },
};
</script>

<style scoped>
.demo {
  min-height: 50vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #ddd;
}

.framework {
  box-sizing: border-box;
  width: 100%;
  /* height: 0; */
  overflow: auto;
}

.content-wrapper {
  width: 100%;
  max-width: 800px;
  padding: 20px;
  box-sizing: border-box;
  text-align: center;
}

h2 {
  color: #42b883;
}

.navigation {
  margin-top: 20px;
}

a {
  text-decoration: none;
  margin: 0 5px;
}
</style>